import useTableList from '@/utils/useTableList';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Col,
  DatePicker,
  Flex,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Upload,
  Image,
} from 'antd';
import React from 'react';
import styles from './index.less';
import {
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import useEditModal from '@/utils/useEditModal';
import { getAdListApi, saveAdApi } from '@/services/ad';
import { uploadApi } from '@/services/file';
import SelectImageButton from '@/components/SelectImageButton';

const Company: React.FC = () => {
  const { loading, form, datasource, page, pageSize, total, onFinish, onPageChange } = useTableList(
    { fetchApi: getAdListApi },
  );

  const {
    loading: editLoading,
    form: editForm,
    currentData,
    setCurrentData,
    onSave,
    onCancel,
  } = useEditModal({
    editApi: saveAdApi,
    addApi: saveAdApi,
    successCb: () => onPageChange(page),
  });

  const image = Form.useWatch('image', editForm);

  const columns: ColumnsType<any> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '广告类型',
      dataIndex: 'typeName',
      key: 'typeName',
      width: 100,
    },
    {
      title: '广告名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '广告图片',
      dataIndex: 'pictureUrl',
      key: 'pictureUrl',
      render: (url: string, row: any) => {
        return url ? <Image src={url} alt={row.name} width={'100%'} /> : '-';
      },
      width: 150,
    },
    {
      title: '广告内容',
      dataIndex: 'content',
      key: 'content',
      render: (content: string) => {
        return <div style={{ whiteSpace: 'pre-wrap' }}>{content}</div>;
      },
    },
    {
      title: '广告链接',
      dataIndex: 'url',
      key: 'url',
      render: (url: string) => {
        return <div style={{ wordBreak: 'break-all' }}>{url}</div>;
      },
    },
    {
      title: '生效时间',
      dataIndex: 'time',
      key: 'time',
      width: 200,
      align: 'center',
      render: (status: number, row: any) => {
        return (
          <Flex vertical gap={5} align="center" justify="center">
            <div>{`${dayjs(row.startTime).format('YYYY-MM-DD HH:mm:ss')}`}</div>
            <div>~</div>
            <div>{`${dayjs(row.endTime).format('YYYY-MM-DD HH:mm:ss')}`}</div>
          </Flex>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                setCurrentData({
                  name: row.name,
                  type: row.type,
                  content: row.content,
                  url: row.url,
                  id: row.id,
                  time: [dayjs(row.startTime), dayjs(row.endTime)],
                  image: row.pictureId
                    ? {
                        pictureId: row.pictureId,
                        pictureUrl: row.pictureUrl,
                      }
                    : undefined,
                });
              }}
            >
              编辑
            </Button>
          </Space>
        );
      },
    },
  ];

  const beforeUpload = async (file: File) => {
    const data = new FormData();
    data.append('file', file, file.name);
    data.append('sourceType', '2');
    const { rsCode, body } = await uploadApi(data);
    if (rsCode === '00000000' && body) {
      editForm.setFieldValue('image', {
        pictureUrl: body.url,
        pictureId: body.id,
      });
    }
    return false;
  };

  const onOk = () => {
    editForm
      .validateFields()
      .then((v: any) => {
        const query: any = {
          id: currentData.id,
          name: v.name,
          type: v.type,
          content: v.content || '-',
          url: v.url || '-',
        };
        if (v.image?.pictureId) {
          query.pictureId = v.image.pictureId;
        }
        if (v.time) {
          query.startTime = dayjs(v.time[0]).format('YYYY-MM-DD HH:mm:ss');
          query.endTime = dayjs(v.time[1]).format('YYYY-MM-DD HH:mm:ss');
        }
        onSave(query);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={(v) => {
              const query: any = {
                name: v.name,
                type: v.type,
              };
              if (v.time) {
                query.startTime = dayjs(v.time[0]).format('YYYY-MM-DD 00:00:00');
                query.endTime = dayjs(v.time[1]).format('YYYY-MM-DD 23:59:59');
              }
              onFinish(query);
            }}
            onReset={() => onFinish({})}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="广告名称" name="name">
                  <Input placeholder="请输入广告名称" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="广告类型" name="type">
                  <Select
                    options={[
                      {
                        value: 1,
                        label: '广告',
                      },
                      {
                        value: 2,
                        label: '公告',
                      },
                      {
                        value: 3,
                        label: '版本升级公告',
                      },
                    ]}
                    placeholder="请选择"
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="生效时间" name="time">
                  <DatePicker.RangePicker
                    placeholder={['开始时间', '结束时间']}
                    allowClear
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={24} xxl={6}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<PlusOutlined />}
                    onClick={() => setCurrentData({})}
                  >
                    新增
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 1250 }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Modal
        title={currentData?.id ? '编辑广告' : '新增广告'}
        centered
        width={800}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        okButtonProps={{ loading: editLoading }}
      >
        <Form
          form={editForm}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          style={{ padding: '20px 0' }}
        >
          <Form.Item label="ID" name="id" hidden />
          <Form.Item
            label="广告名称"
            name="name"
            rules={[{ required: true, message: '请输入广告名称' }]}
          >
            <Input placeholder="请输入广告名称" />
          </Form.Item>
          <Form.Item
            label="广告类型"
            name="type"
            rules={[{ required: true, message: '请选择广告类型' }]}
          >
            <Select
              options={[
                {
                  value: 1,
                  label: '广告',
                },
                {
                  value: 2,
                  label: '公告',
                },
                {
                  value: 3,
                  label: '版本升级公告',
                },
              ]}
              placeholder="请选择广告类型"
              allowClear
            />
          </Form.Item>
          <Form.Item
            label="生效时间"
            name="time"
            rules={[{ required: true, message: '请选择生效时间' }]}
          >
            <DatePicker.RangePicker
              showTime
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="广告内容" name="content">
            <Input.TextArea placeholder="请输入广告内容" rows={5} />
          </Form.Item>
          <Form.Item label="广告链接" name="url">
            <Input placeholder="请输入广告链接" />
          </Form.Item>
          <Form.Item label="广告图片">
            <Space direction="vertical" size={15}>
              <Flex align="center" justify="flex-start" gap={15}>
                <Upload
                  accept=".jpg,.bmp,.png,.jpeg"
                  beforeUpload={beforeUpload}
                  showUploadList={false}
                >
                  <Button icon={<UploadOutlined />} type="primary">
                    上传图片
                  </Button>
                </Upload>
                <SelectImageButton
                  onSelect={function (data: any[]): void {
                    const item = data[0];
                    if (item) {
                      editForm.setFieldValue('image', {
                        pictureUrl: item.filePath,
                        pictureId: item.id,
                      });
                    }
                  }}
                />
              </Flex>
              <Form.Item noStyle name="image">
                {image?.pictureUrl && (
                  <div className={styles.image_box}>
                    <Image width={'100%'} src={image?.pictureUrl} />
                    <DeleteFilled
                      className={styles.delete_icon}
                      onClick={() => editForm.setFieldValue('image', undefined)}
                    />
                  </div>
                )}
              </Form.Item>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Company;
